﻿using System;
using System.Collections.Generic;
using EnvDTE;
using EnvDTE80;


namespace VsTortoiseSVN.Commands
{
    public class CommandManager
    {
        private Dictionary<string, CommandBase> _commands;
        private DTE2 _application { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        public CommandManager(DTE2 app)
        {
            _commands = new Dictionary<string, CommandBase>();
            _application = app;
        }

        /// <summary>
        /// Adds a command to the manager.
        /// </summary>
        /// <param name="fullname">Full qualified name including the ProgId value</param>
        /// <param name="command">Reference to the command to add</param>
        public void Add(string fullname, CommandBase command)
        {
            _commands[fullname] = command;
        }

        /// <summary>
        /// Gets status of the command with the specified full name.
        /// Whenever a command button is about to appear, Visual Studio
        /// queries its status.
        /// </summary>
        public vsCommandStatus QueryStatus(string fullname)
        {
            if (IsPresent(fullname))
                return _commands[fullname].QueryStatus();

            return vsCommandStatus.vsCommandStatusUnsupported;
        }

        /// <summary>
        /// Executes the command with the specified full name.
        /// </summary>
        public bool Exec(string fullname)
        {
            if (IsPresent(fullname))
            {
                CommandBase command = _commands[fullname];
                if (command.SaveRequired)
                {
                    if (!_application.SaveDocuments())
                        return false;
                }

                return command.Exec();
            }

            return false;
        }

        /// <summary>
        /// Checks whether the command with the specified full name exists.
        /// </summary>
        public bool IsPresent(string fullname)
        {
            return _commands.ContainsKey(fullname);
        }
    }
}
